<template>
  <view class="technician container-normal">
    <view class="technician-header flex">
      <view class="area flex">
        <span style="margin-right: 10rpx; font-size: 26rpx; color: #333">
          长沙市
        </span>
        <u-icon name="arrow-down-fill" size="10" color="#B8B8B8"></u-icon>
      </view>
      <u--input
        placeholder="请输入技师姓名"
        prefixIcon="search"
        shape="circle"
        @blur="getSearchListData"
        border="none"
        :customStyle="searchInputBorder"
        prefixIconStyle="font-size: 22px;color: #909399"
      ></u--input>
    </view>

    <view class="technician-tabs">
      <!-- tabs -->
      <MyTabs
        :list="tabList"
        @change="handleChange"
        @initList="handleInitList"
      />
    </view>

    <view class="technician-list">
      <view
        class="technician-list-item flex flex-item-center"
        v-for="(server, index) of showNewServerList"
        @click.stop="handleUserInfoDetail(server._id, server.technician_Info)"
        :key="index"
      >
        <image
          v-if="server.work_img.length"
          class="flex-shrink-0"
          :src="$photo(server.work_img)"
        />
        <view class="technician-list-item-right flex-1">
          <view class="person flex flex-item-center flex-justify-between">
            <view class="person-message flex">
              <view class="name">{{ server.nickname }}</view>
              <view
                class="status"
                :class="server.technician_status === 0 ? 'end-status' : ''"
              >
                {{
                  server.technician_status > 0
                    ? server.technician_status > 1
                      ? "服务中"
                      : "可服务"
                    : "不可服务"
                }}
              </view>
            </view>
            <view class="distance flex">
              <u-icon name="map-fill" size="20" color="#C5C5C5"></u-icon>
              <span style="margin-left: 8rpx" v-if="server.technician_address">
                {{
                  $helper.distance(
                    server.technician_address.split(",")[0],
                    server.technician_address.split(",")[1],
                    location
                  )
                }}km
              </span>
            </view>
          </view>

          <view class="flex flex-item-center">
            <view v-if="getAverageScore(server._id)">
              <u-icon name="star-fill" color="#F7CF51" size="20"></u-icon>
              <span class="star-number" style="margin-left: 8rpx">{{
                getAverageScore(server._id)
              }}</span>
            </view>
            <view style="color: #666" v-else>暂未参与评分</view>
          </view>

          <view class="flex flex-item-center flex-justify-between">
            <view class="evaluate">
              订单
              <text v-if="filterOrderData[server._id]">
                {{
                  filterOrderData[server._id].length
                    ? Number(filterOrderData[server._id].length) > 100
                      ? "100+"
                      : filterOrderData[server._id].length
                    : 0
                }}
              </text>
              <text v-else>0 </text>
              | 评价
              <text v-if="filterEvaluateData[server._id]">
                {{
                  filterEvaluateData[server._id].length
                    ? Number(filterEvaluateData[server._id].length) > 500
                      ? "500+"
                      : filterEvaluateData[server._id].length
                    : 0
                }}
              </text>
              <text v-else>0 </text>
            </view>
            <button
              class="circle-button home-btn"
              :disabled="server.technician_status === 0"
              @click.stop="handleReserveBtn(server)"
            >
              立即预约
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部弹出层 -->
    <u-popup :show="show" @close="show = false">
      <view class="popup-container" v-if="detailData">
        <view class="popup-container-header flex flex-item-center">
          <image
            v-if="currentProject"
            :src="$photo(currentProject.project_log)"
            alt=""
          />
          <view class="header-right">
            <view class="header-right-title">{{ currentProject.title }}</view>
            <view class="header-right-effect flex flex-item-center">
              <span>{{ currentProject.project_time + "分钟&nbsp;" }}</span>
              <span v-for="(item, index) of currentProject.effect" :key="index">
                | {{ item + "&nbsp;" }}
              </span>
            </view>
            <view class="header-right-price">
              <span>¥</span> {{ currentProject.price }}
            </view>
          </view>
        </view>
        <view class="popup-container-body">
          <view class="service-items">
            <view class="flex flex-item-center justify-between">
              <view class="service-items-title">服务项目</view>
              <view class="flex flex-item-center" @click="handleShowPick">
                <u-icon name="clock-fill" color="#C5C5C5"></u-icon>
                <view class="time-range flex flex-item-center">
                  <text>{{
                    $u.timeFormat(selectTimeValue, "mm-dd hh:MM")
                  }}</text>
                  -
                  <text>{{
                    $u.timeFormat(
                      selectTimeValue + currentProject.project_time * 60 * 1000,
                      "mm-dd hh:MM"
                    )
                  }}</text>
                </view>
                <u-icon name="arrow-right" color="#C5C5C5"></u-icon>
              </view>
            </view>

            <view class="flex flex-item-center" style="padding-top: 20rpx">
              <view
                v-for="(project, index) of inCludesProjectList"
                :key="index"
                class="project-item"
                :class="
                  currentProject.title === project.name ? 'active-item' : ''
                "
                @click="handleCurrentProject(project.id)"
              >
                {{ project.name }}
              </view>
            </view>
          </view>
        </view>
        <view class="popup-container-footer">
          <!-- 详情页底部提交 -->
          <view
            class="popup-container-footer-submit flex flex-item-center justify-between"
          >
            <view class="flex flex-item-center order-price">
              合计: <span>¥ </span>
              <text>{{ currentProject.price }}</text>
            </view>
            <view class="submit-btn" @click="createOrderModel">去下单</view>
          </view>
        </view>
      </view>
      <u-empty
        v-else
        mode="data"
        icon="http://cdn.uviewui.com/uview/empty/data.png"
      >
      </u-empty>
    </u-popup>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showTime"
      v-model="selectTimeValue"
      @cancel="showTime = false"
      @confirm="handleSelectTime"
      mode="datetime"
    ></u-datetime-picker>

    <!-- 提示弹框 -->
    <u-overlay :show="isShow" @click="isShow = false">
      <view class="technician-warp">
        <OrderModel :width="450" :height="386">
          <template slot="title">
            <!-- <view></view> -->
            <view class="model-title"> </view>
          </template>
          <template slot="content">
            <view class="model-content"> 30分钟 </view>
            <view class="model-tips text-ellipsis"> 总共需要等待时长 </view>
          </template>
          <template slot="footer">
            <view class="model-footer flex flex-item-center justify-around">
              <button
                class="circle-button normal-button"
                @click.stop="isShow = false"
              >
                取消
              </button>
              <button
                class="circle-button btn-active"
                @click.stop="createOrder(detailData)"
              >
                确定
              </button>
            </view>
          </template>
        </OrderModel>
      </view>
    </u-overlay>
  </view>
</template>

<script>
import { getModelList, getModelInfo } from "@/api";
import { getSearchFilter } from "@/common/function";
import { mapState } from "vuex";
import MyTabs from "@/components/MyTabs/MyTabs.vue";
import OrderModel from "@/components/OrderModel/OrderModel.vue";

export default {
  components: {
    MyTabs,
    OrderModel,
  },
  data() {
    return {
      searchInputBorder: {
        "box-shadow": "0px 2px 14px 1px rgba(190,190,190,0.3)",
        height: "68rpx",
        "padding-left": "20rpx",
      },
      tabList: [
        {
          name: "综合排序",
          status: true,
        },
        {
          name: "服务量",
          status: true,
        },
        {
          name: "好评度",
          status: true,
        },
      ],
      show: false, //显示项目弹出层
      showTime: false, //显示日期选择
      isShow: false, //显示提示弹窗
      currentProject: {}, //当前选择的项目
      detailData: null, // 过滤参数
      allOrderData: [], // 全部订单数据
      allEvaluateData: [], // 全部评价数据
      newServerList: [], // 新技师列表数据 接受请求回来的
      showNewServerList: [], //展示列表的
      inCludesProjectList: [], // 技师包含项目
      selectTimeValue: Date.now(), //选择当前项目时间
      servingOrder: null, // 当前服务订单
      projectId: null, // 当前项目id
    };
  },
  computed: {
    ...mapState("address", ["currentAddress"]),
    // 整理订单数筛选
    filterOrderData() {
      return this.$helper.handleFilterData(this.allOrderData, "technician_id");
    },
    // 整理评价数筛选
    filterEvaluateData() {
      return this.$helper.handleFilterData(this.allEvaluateData, "server_id");
    },
    // 得到默认地址经纬度
    location() {
      let arr = this.currentAddress?.location?.split(",");
      return {
        lat: arr?.[1] || 0,
        lng: arr?.[0] || 0,
      };
    },
  },
  watch: {},
  methods: {
    async handleReserveBtn(userData) {
      this.detailData = userData;
      // 跟新展示时间
      this.selectTimeValue = Date.now();
      this.inCludesProjectList = this.handleCurrentData(
        userData.includes_project
      );
      let projectId = this.inCludesProjectList?.[0]?.id;
      this.currentProject = await this.getProjectInfo(projectId);
      this.show = true;
    },
    // 选择项目
    async handleCurrentProject(id) {
      this.currentProject = await this.getProjectInfo(id);
    },
    // tabs切换
    async handleChange({ data, index }) {
      this.tabList[index] = data;
      switch (data.name) {
        case "服务量":
          sortObj = {
            service_number: this.tabList[index].status ? "asc" : "desc",
          };
          break;
        case "好评度":
          sortObj = { praise: this.tabList[index].status ? "asc" : "desc" };

          break;
        case "综合排序":
          sortObj = {
            score: this.tabList[index].status ? "asc" : "desc",
          };
          break;
        default:
          sortObj = {};
      }
      // 数组筛选
    },
    // 初始化tabs
    handleInitList(list) {
      this.tabList = list;
    },
    // 搜索框
    getSearchListData(nickname) {
      this.showNewServerList = this.newServerList.filter((item) => {
        return item.nickname.includes(nickname);
      });
    },
    // 显示创建订单弹窗
    async createOrderModel() {
      // 平判断所选时间是否合适
      let res = await this.handleTimeRangeOk(this.selectTimeValue);
      console.log(res);
      if (!res) return;
      this.show = false;
      this.isShow = true;
    },
    // 确定创建订单
    async createOrder(data) {
      let { technician_address, technician_Info } = data;
      // 获取距离
      let currentDistance = this.$helper.distance(
        technician_address?.split(",")[0],
        technician_address?.split(",")[1],
        this.location
      );
      // 要传递的数据
      let dataObject = {
        technician_id: technician_Info,
        project_id: this.currentProject._id,
        distance_number: Number(currentDistance),
        selectTimeValue: this.selectTimeValue, //客户选择服务时间
      };
      // 整理特殊复杂
      let orderData = decodeURIComponent(JSON.stringify(dataObject));
      this.isShow = false;
      uni.navigateTo({
        url: `/subPages/user/order/create-order?orderData=${orderData}`,
      });
    },
    // 技师详情
    handleUserInfoDetail(serveId, infoId) {
      this.isShow = false;
      this.$jump("/subPages/home/technician-detail/technician-detail", {
        query: { serveId, infoId },
      });
    },
    // 获取成绩平均值
    getAverageScore(id, key = "score") {
      let result = (
        this.filterEvaluateData[id]?.reduce(
          (total, item) => total + item[key],
          0
        ) / this.filterEvaluateData[id]?.length
      ).toFixed(2);

      return isNaN(result) ? 0 : Number(result);
    },
    // 获取新表数据
    async getNewServerData(filterData) {
      console.log("餐宿", filterData);
      let filter = Object.keys(filterData)
        .map((item) => {
          return getSearchFilter(
            { [item]: filterData[item] },
            { method: "like" }
          );
        })
        .flat(2);

      let arr = [];
      const { data } = await getModelList("65fbe6475efd5153ff566a8b", {
        currentPage: 1,
        pageSize: -1,
        filter,
        sort: {
          technician_status: "desc",
        },
      });
      for (const item of data?.list) {
        switch (item.technician_status) {
          case 0:
            item.status = "不可服务";
            break;
          case 1:
            item.status = "可服务";
            break;
          default:
            item.status = "服务中";
        }
        let info = await this.getTechnicianBaseInfo(item.technician_Info);
        arr.push({ ...info, ...item });
      }

      this.newServerList = arr;
      this.showNewServerList = arr;
    },
    // 获取当前技师基础信息请求
    async getTechnicianBaseInfo(id) {
      const { data } = await getModelList("65c08a445efd5153ff55d908", {
        currentPage: 1,
        pageSize: -1,
        filter: getSearchFilter({ _id: id }, { method: "eq" }),
      });
      return data?.list[0];
    },
    // 获取项目信息
    async getProjectInfo(id) {
      const { data, code } = await getModelInfo("65b1d17c0921260197c48a76", id);
      if (code === 200) return data;
    },
    // 整理获取弹出层数据
    handleCurrentData(arr) {
      return arr?.map((item) => {
        let [id, name] = item.split("/");
        return {
          id,
          name,
        };
      });
    },
    // 抽离判断时间段是否合适方法
    async handleTimeRangeOk(value) {
      let startTime = value;
      let filter = {
        currentPage: 1,
        pageSize: -1,
        connect: "and",
        filter: [
          getSearchFilter(
            { baseInfo_id: this.detailData.technician_Info },
            { method: "eq" }
          ),
        ].flat(2),
        sort: {
          start_time: "desc",
        },
      };
      try {
        // 获取当前技师当前服务的项目结束时间
        const { data, code } = await getModelList(
          "66002f4f5efd5153ff566ec3",
          filter
        );
        if (code === 200) {
          this.servingOrder = data?.list?.[0];
          let endTime = this.servingOrder?.start_time + 70 * 60 * 1000; //当前服务结束
          if (endTime < startTime || !this.servingOrder) {
            // 如果当前服务结束时间小于选择时间，或者当前服务没有结束
            this.selectTimeValue = startTime;
            return true; //结束函数执行
          } else {
            this.$message(
              `该时间冲突,请选择${uni.$u.timeFormat(
                endTime,
                "yyyy-mm-dd hh:MM"
              )}以后的时间`,
              false,
              { duration: 3000 }
            );
            return false; //结束函数执行
          }
        }
      } catch (err) {
        console.log(err);
      } finally {
        this.showTime = false;
      }
    },
    //发送请求获取技师当前服务项目 选择项目服务时间段
    async handleSelectTime({ value }) {
      // console.log(value);
      await this.handleTimeRangeOk(value);
    },
    //展示时间选择器
    handleShowPick() {
      this.selectTimeValue = Date.now();
      this.showTime = true;
    },
  },
  async onShow() {
    let that = this;
    await Promise.all([
      this.getNewServerData({
        includes_project: that.projectId,
      }),
    ]);
    // 获取用户当前位置
    await this.$store.dispatch("address/getCurrentLocationData", {
      creatorUserId: this.$storage.get("UserInfo").id,
    });
  },
  onLoad({ projectId }) {
    // //获取到项目id
    console.log(projectId);
    this.projectId = projectId;
  },
};
</script>

<style lang="scss" scoped>
.technician {
  position: relative;
  width: 100%;

  &-warp {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;

    .model-title {
      font-size: 40rpx;
      font-weight: bold;
      color: #000000;
      text-align: center;
      margin-top: 100rpx;
    }

    .model-content {
      padding: 20rpx 0;
      font-size: 34rpx;
      text-align: center;
    }

    .model-tips {
      box-sizing: border-box;
      padding: 0 20rpx;
      margin: 10rpx 0;
      font-size: 28rpx;
      color: #999999;
      text-align: center;
      overflow: hidden;
    }

    .model-footer {
      padding-top: 10rpx;
      > button {
        width: 158rpx;
        height: 58rpx;
        line-height: 58rpx;
        font-size: 26rpx;
        text-align: center;
        color: #ffffff;
      }
    }
  }

  &-header {
    justify-content: space-around;
    align-items: center;
    margin-bottom: 30rpx;

    .area {
      width: 144rpx;
    }
  }

  &-tabs {
    margin: 20rpx 0;
  }

  &-list {
    &-item {
      padding: 20rpx 0 40rpx 0;
      border-bottom: 1px solid #c5c5c5;

      &:last-child {
        border: none;
      }

      > image {
        width: 150rpx;
        height: 150rpx;
        border-radius: 50%;
        margin-right: 24rpx;
      }

      &-right {
        > view {
          margin-bottom: 20rpx;

          &:last-child {
            margin: 0;
          }
        }

        .person {
          &-message {
            .name {
              font-size: 28rpx;
              font-weight: bold;
              color: #333333;
              margin-right: 20rpx;
            }
            .status {
              width: 124rpx;
              height: 38rpx;
              line-height: 38rpx;
              text-align: center;
              border-radius: 38rpx;
              background: #f7ece8;
              border: 1px solid #c94117;
              font-size: 24rpx;
              color: #c94117;
            }
          }
        }

        .evaluate {
          font-size: 26rpx;
          color: #999999;

          > text {
            padding-right: 16rpx;
          }
        }

        .star-number {
          color: #ffcd2a;
        }
      }
    }
  }
}

/* 弹出层样式 */
.popup-container {
  padding: 30rpx;

  &-header {
    padding-bottom: 30rpx;
    border-bottom: 1px solid #e3e3e3;

    > image {
      width: 170rpx;
      height: 126rpx;
      margin-right: 26rpx;
    }

    .header-right {
      > view {
        margin-bottom: 10rpx;

        &:last-of-type {
          margin: 0;
        }
      }

      &-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      &-effect {
        font-size: 26rpx;
        color: #999999;
      }

      &-price {
        font-size: 32rpx;
        font-weight: 800;
        color: #e20808;

        > span {
          font-size: 20rpx;
          margin-right: 12rpx;
        }
      }
    }
  }

  &-body {
    .service-items {
      padding: 30rpx 0;
      border-bottom: 1px solid #e3e3e3;

      &-title {
        font-size: 30rpx;
        color: #333333;
      }

      .time-range {
        > text {
          color: #e80000;
          font-size: 26rpx;
          margin: 0 10rpx;
        }
      }

      .project-item {
        width: 150rpx;
        height: 50rpx;
        text-align: center;
        margin-right: 30rpx;
        line-height: 50rpx;
        border-radius: 25rpx;
        border: 1px solid #c5c5c5;
        color: #c5c5c5;
        font-size: 26rpx;
      }
    }
  }

  &-footer {
    &-submit {
      padding-top: 30rpx;
      box-sizing: border-box;

      .order-price {
        color: #999;
        font-size: 26rpx;

        > span {
          color: #e20808;
          font-size: 22rpx;
          margin: 0 10rpx;
        }

        > text {
          color: #e20808;
          font-size: 30rpx;
        }
      }

      .submit-btn {
        width: 260rpx;
        height: 88rpx;
        line-height: 88rpx;
        background: #c94117;
        border-radius: 44rpx;
        text-align: center;
        color: #fff;
        font-size: 38rpx;

        &:active {
          transform: scale(0.98);
        }
      }
    }
  }
}

// 去掉烦人的边框
button::after {
  border: 0; // 或者 border: none;
}

// 调整禁用时的样式
button[disabled] {
  background-color: #e3e3e3;
}
.active-item {
  background: rgba(201, 65, 23, 0.1) !important;
  // border: 1px solid #c94117 !important;
  color: #c94117 !important;
}

.minus {
  width: 22px;
  height: 22px;
  border-width: 1px;
  border-color: #e6e6e6;
  border-style: solid;
  border-top-left-radius: 100px;
  border-top-right-radius: 100px;
  border-bottom-left-radius: 100px;
  border-bottom-right-radius: 100px;
  @include flex;
  justify-content: center;
  align-items: center;
}

.input {
  padding: 0 10px;
}

.plus {
  width: 22px;
  height: 22px;
  background-color: #ff0000;
  border-radius: 50%;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  justify-content: center;
  align-items: center;
}

.end-status {
  background-color: #e5e5e5 !important;
  color: #999999 !important;
  border-color: #e5e5e5 !important;
}
</style>
